package com.ciwong.epaper.widget.evaluate;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.ui.WordBottomView;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.WordUtil;
import com.ciwong.epaper.widget.ColorationTextView;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.DeviceUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 单词跟读文本
 *
 * @author jejun
 * @version ciwong v.1.0 2014-2-11
 * @since ciwong v.1.0
 */
public class UnitSpeechView extends BaseFrameLayout implements OnPageChangeListener {
	private WorkViewPager viewPager;

	private List<Sentence> wordDatas;

	private TextView scoreView;

	private int currentPageIndex;

	private LayoutInflater inflater;

	private int defaultWordColor;

	private int scoreDefColor;// 评分结果颜色

	private OnPageSelectChangeListener mSelelectChangeListener;

	private static final String TAG = "UnitSpeechView";


	public UnitSpeechView(Context context) {
		super(context);
		init();
	}

	public UnitSpeechView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public UnitSpeechView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		viewPager = new WorkViewPager(getContext());
		addView(viewPager);
		viewPager.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
		inflater = LayoutInflater.from(getContext());
		viewPager.setCanScroll(false);
		viewPager.setVerticalScrollBarEnabled(false);
		viewPager.setHorizontalScrollBarEnabled(false);
		viewPager.setOnPageChangeListener(this);
		defaultWordColor = getContext().getResources().getColor(R.color.default_text_color);
		scoreDefColor = 0xff999999;
	}

	/**
	 * 是否可以滚动
	 *
	 * @param canScroll
	 */
	public void setCanScroll(boolean canScroll) {
		viewPager.setCanScroll(canScroll);
	}

	/**
	 * 设置显示数据源
	 *
	 * @param words
	 * @param
	 * @param scoreView
	 * @param userId
	 * @param currPage
	 */
	public void setData(List<WordDetail> words, WordBottomView wordBottomView, TextView scoreView, long userId, int currPage) {
		initData(wordBottomView, userId);
		this.scoreView = scoreView;
		int len = words == null ? 0 : words.size();
		wordDatas = new ArrayList<Sentence>();
		for (int i = 0; i < len; i++) {
			WordDetail word = words.get(i);
			String wStr = word.getWords();
			String[] arr = SpeechUtils.replaceAsSpace(wStr).split(" ");
			List<WordDetail> ws = new ArrayList<WordDetail>();
			Sentence sentence = new Sentence();
			for (String str : arr) {
				WordDetail w = new WordDetail();
				w.setPretations(word.getPretations());
				w.setSentences(word.getSentences());
				w.setSentFile(word.getSentFile());
				w.setText(str);
				w.setSyllable(word.getSyllable());
				w.setSymbol(word.getSymbol());
				w.setwId(word.getwId());
				w.setWordFile(word.getWordFile());
				sentence.setSentenceMp3(w.getWordFile());
				w.setWordPic(word.getWordPic());
				w.setWordType(word.getWordType());
				w.setColor(defaultWordColor);
				ws.add(w);
			}
			sentence.setWordDetails(ws);
			sentence.setText(wStr);
			wordDatas.add(sentence);
		}
		ViewPageAdapter adapter = new ViewPageAdapter();
		viewPager.setAdapter(adapter);
		currentPageIndex = currPage;
		viewPager.setCurrentItem(currPage);
	}

	private int pageSize() {
		return wordDatas == null ? 0 : wordDatas.size();
	}

	/**
	 * 下一页
	 */
	public void next() {
		currentPageIndex++;
		if (currentPageIndex >= pageSize()) {
			currentPageIndex = pageSize() - 1;
			return;
		}
		animTo(currentPageIndex);
	}


	/**
	 * 滚动到指定界面
	 *
	 * @param index 索引
	 */
	public void animTo(int index) {
		currentPageIndex = index;
		viewPager.setCurrentItem(index, true);
	}

	/**
	 * 显示指定界面
	 *
	 * @param index 索引
	 */
	public void smoothTo(int index) {
		currentPageIndex = index;
		viewPager.setCurrentItem(index, false);
	}

	/**
	 * 恢复当前单词的颜色(初始设置值)
	 */
	public void resetCurrentWordColor() {
		setCurrentWordColor(defaultWordColor);
	}

	/**
	 * 显示评测结果
	 *
	 * @param er {@link EvaluateResult}
	 */
	public void showResult(EvaluateResult er) {
		SpeechTextView speechView = getCurrentSpeech();
		if (speechView == null) {
			Log.e("debug", "showResult speechView nnull");
			return;
		}
		Sentence sentence = speechView.getSentence();
		sentence = WordUtil.dealWordColoration(er, sentence);
		speechView.setSentence(sentence, scoreView, false);
		speechView.setTextColor(getResources().getColor(R.color.repeat_read_gray));
	}


	public void setSymbolColoration(EvaluateResult eResult) {
		TextView curentSymbolTextView = getCurentSymbolTextView();
		if (curentSymbolTextView != null && curentSymbolTextView instanceof ColorationTextView) {
			ColorationTextView colorTextView = (ColorationTextView) curentSymbolTextView;
			colorTextView.setSymbolColoration(eResult, getCurrentOriginSysmbol());
			//h5格式解析染色
			//            colorTextView.setSymbolColorationByHtml(eResult);
		}
	}


	/**
	 * 恢复初始颜色
	 */
	public void resetWordColor() {
		for (Sentence s : wordDatas) {
			s.setHasGrade(false);
			for (WordDetail w : s.getWordDetails()) {
				w.setColor(defaultWordColor);
			}
		}
		int len = viewPager.getChildCount();
		for (int i = 0; i < len; i++) {
			View view = viewPager.getChildAt(i);
			UnitSpeechHolder holder = (UnitSpeechHolder) view.getTag(R.string.speech_tag_holder);
			int index = Integer.parseInt(view.getTag().toString());
			holder.speech.setSentence(wordDatas.get(index));
		}
	}

	/**
	 * 重置当前单词
	 */
	public void resetCurrWord() {
		SpeechTextView currentSpeech = getCurrentSpeech();
		Sentence sentence = currentSpeech.getSentence();
		sentence.setHasGrade(false);
		currentSpeech.setSentence(sentence);
	}

	/**
	 * 设置当前单词的颜色
	 *
	 * @param color 颜色值
	 */
	public void setCurrentWordColor(int color) {
		SpeechTextView speechView = getCurrentSpeech();
		if (speechView == null) {
			return;
		}
		Sentence sentence = speechView.getSentence();
		for (WordDetail w : sentence.getWordDetails()) {
			w.setColor(color);
		}
		speechView.setSentence(sentence);
	}

	/**
	 * 获取当前的SpeechTextView
	 *
	 * @return {@link SpeechTextView}
	 */
	public SpeechTextView getCurrentSpeech() {
		return getSpeechTextView(viewPager.getCurrentItem());
	}

	public String getCurrentOriginSysmbol() {
		try {
			if (wordDatas != null && wordDatas.size() > 0) {
				Sentence sentence = wordDatas.get(viewPager.getCurrentItem());
				WordDetail word = sentence.getWordDetails().get(0);
				String symbol = word.getSymbol();
				if (symbol != null) {
					if (!symbol.startsWith("[")) {
						symbol = "[" + symbol;
					}
					if (!symbol.endsWith("]")) {
						symbol += "]";
					}
				}
				return symbol;
			}
		} catch (Exception e) {
			return "[]";
		}
		return "[]";
	}


	private UnitSpeechHolder getUnitSpeechHolder(int position) {
		View cur = viewPager.findViewWithTag(position);
		if (cur == null) {
			return null;
		}
		UnitSpeechHolder holder = (UnitSpeechHolder) cur.getTag(R.string.speech_tag_holder);
		return holder;
	}

	/**
	 * 获取指定索引的 SpeechTextView
	 *
	 * @param position 指定索引
	 * @return {@link SpeechTextView}
	 */
	public SpeechTextView getSpeechTextView(int position) {
		UnitSpeechHolder holder = getUnitSpeechHolder(position);
		return holder == null ? null : holder.speech;
	}

	public TextView getCurentSymbolTextView() {
		UnitSpeechHolder holder = getUnitSpeechHolder(viewPager.getCurrentItem());
		return holder == null ? null : holder.symbol;
	}

	/**
	 * 页码发生变化
	 *
	 * @param listener
	 */
	public void setOnPageSelectChangeListener(OnPageSelectChangeListener listener) {
		mSelelectChangeListener = listener;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int index) {
		if (mSelelectChangeListener != null) {
			mSelelectChangeListener.onPageSelected(index);
		}
	}

	/**
	 * 设置分贝
	 *
	 * @param rms 分贝值
	 */
	public void setRms(double rms) {
		// UnitSpeechHolder holder = getUnitSpeechHolder(currentPageIndex);
		// if (holder != null)
		// {
		// holder.speech.setRms(rms);
		// holder.bottomSpeech.setRms(rms);
		// }
	}

	public Sentence getSentence() {
		Sentence sentence = new Sentence();
		SpeechTextView speechView = getCurrentSpeech();
		if (speechView != null) {
			 sentence = speechView.getSentence();
		}
		return sentence;
	}

	public class ViewPageAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			return wordDatas == null ? 0 : wordDatas.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			CWLog.d("debug", "destroyItem:" + object);
			container.removeView((ScrollView) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			CWLog.d("debug", "instantiateItem");
			final UnitSpeechHolder holder = new UnitSpeechHolder();
			holder.spokenContainer = inflater.inflate(R.layout.unit_speech, null);
			container.addView(holder.spokenContainer);
			holder.unitPic = (ImageView) holder.spokenContainer.findViewById(R.id.unitPic);
			holder.speech = (SpeechTextView) holder.spokenContainer.findViewById(R.id.speech);
			holder.symbol = (ColorationTextView) holder.spokenContainer.findViewById(R.id.symbol);
			holder.pretations = (TextView) holder.spokenContainer.findViewById(R.id.pretations);
			holder.sentences = (TextView) holder.spokenContainer.findViewById(R.id.sentences);
			holder.vLine = holder.spokenContainer.findViewById(R.id.view_line);
			holder.tvExampleSentence = (TextView) holder.spokenContainer.findViewById(R.id.tv_example_sentence);
			holder.spokenContainer.setTag(position);
			holder.spokenContainer.setTag(R.string.speech_tag_holder, holder);
			Sentence sentence = wordDatas.get(position);
			WordDetail word = sentence.getWordDetails().get(0);
			String symbol = word.getSymbol();
			if (symbol != null) {
				if (!symbol.startsWith("[")) {
					symbol = "[" + symbol;
				}
				if (!symbol.endsWith("]")) {
					symbol += "]";
				}
				word.setSymbol(symbol);
			}
			holder.symbol.setText(word.getSymbol());
			holder.pretations.setText(word.getPretations());

			holder.tvExampleSentence.setVisibility(VISIBLE);
			holder.vLine.setVisibility(VISIBLE);
			String text = word.getSentences();
			String replaceTxt = text.replace("\r", "\n");
			holder.sentences.setText(replaceTxt);
			if (TextUtils.isEmpty(word.getSentences())) {
				holder.sentences.setText("─");
			}
			//			} else {
			//				holder.vLine.setVisibility(GONE);
			//				holder.tvExampleSentence.setVisibility(GONE);
			//			}

			holder.speech.setScoreColor(scoreDefColor);
			holder.speech.setSentence(sentence);
			ImageSize size = new ImageSize(DeviceUtils.getScreenWdith(), R.dimen.word_pic_height);
			ImageLoader.getInstance().loadImage(ESystem.formatPath(word.getWordPic()), size, new ImageLoadingListener() {
				@Override
				public void onLoadingStarted(String s, View view) {

				}

				@Override
				public void onLoadingFailed(String s, View view, FailReason failReason) {

				}

				@Override
				public void onLoadingComplete(String s, View view, Bitmap bitmap) {
					holder.unitPic.setImageBitmap(bitmap);
				}

				@Override
				public void onLoadingCancelled(String s, View view) {

				}
			});

			return holder.spokenContainer;
		}

		@Override
		public boolean isViewFromObject(View view, Object arg1) {
			return view == arg1;
		}

	}

	public static interface OnPageSelectChangeListener {
		void onPageSelected(int index);
	}

	public static class UnitSpeechHolder {
		public View spokenContainer, vLine;

		public SpeechTextView speech;

		public ImageView unitPic;

		public TextView symbol, pretations, sentences, tvExampleSentence;

		public void copy(UnitSpeechHolder holder) {
			if (holder != null) {
				holder.speech = speech;
				holder.pretations = pretations;
				holder.sentences = sentences;
				holder.spokenContainer = spokenContainer;
				holder.symbol = symbol;
				holder.unitPic = unitPic;
			}
		}
	}

}
